const uniID = require('uni-id-common')

exports.main = async (event, context) => {
  let body = event;
  if (event.body != undefined) {
    body = JSON.parse(event.body)
  }

  const uniIDIns = uniID.createInstance({ context })
  const db = uniCloud.database()

  try {
    // 1. 身份验证，获取 uid
    const { uid } = await uniIDIns.checkToken(body.uniIdToken)
    if (!uid) {
      return { code: 403, msg: '咨询师身份验证失败' }
    }
    let { appointUserId } = body;
	if(!appointUserId){
		return { code: 403, msg: '缺少参数appointUserId' }
	}

    // 2. 查询 goeasy_message 表，筛选出包含该 uid 的消息记录
	const messagesRes = await db.collection('goeasy_messages')
	  .where({
		$or: [
		  { senderId: uid, receiverId: appointUserId },
		  { senderId: appointUserId, receiverId: uid }
		]
	  })
	  .get()

    if (messagesRes.data.length === 0) {
      return { code: 404, msg: '没有符合条件的消息记录' }
    }
	console.log(messagesRes)
    // 3. 获取消息并格式化为文本文档
    let resultText = '咨询师ID: ' + uid + '\n' + '用户ID: ' + appointUserId + '\n\n';  // 先显示ID
    
    for (let msg of messagesRes.data) {
      const senderName = msg.senderId === uid ? '咨询师' : (msg.senderId === appointUserId ? '用户' : '未知发送者');
      const receiverName = msg.receiverId === uid ? '咨询师' : (msg.receiverId === appointUserId ? '用户' : '未知接收者');
      const payload = JSON.parse(msg.payload).text;
    
      // 根据 senderId 判断消息的发送者，并添加到文档中
      if (msg.senderId === uid || msg.senderId === appointUserId) {
        resultText += `${senderName}：${payload}\n`;
      }
    }

    return {
      code: 0,
	  msg: '聊天记录已生成',
      resultText
    }
    
  } catch (e) {
    return { code: 500, msg: '服务器错误', detail: e.message }
  }
}
